import sys
sys.path.append('protosGen')

from config.constants import Constants
from protosGen.marketGateway_pb2_grpc import *
from protosGen.login_pb2 import *
from protosGen.login_pb2_grpc import *
from protosGen.orderreporting_pb2 import *
from protosGen.orderreporting_pb2_grpc import *
import time
from common import header_manipulator_client_interceptor
import signal
import ma_strategy
import position_strategy


class RouweiDemo:
    def __init__(self):
        channelAuth = grpc.insecure_channel(Constants.HOST + ":" + Constants.PORT_AUTH)
        loginStub = LoginStub(channelAuth)
        rspLogin = loginStub.login(ReqLogin(
            username=Constants.USER_NAME,
            password=Constants.USER_PASSWORD))
        if not rspLogin.success:
            print("rspLogin.message:" + str(rspLogin.message))
            print("rspLogin.success:" + str(rspLogin.success))
            print("rspLogin.token:" + str(rspLogin.token))
            return

        header_adder_interceptor = header_manipulator_client_interceptor.header_adder_interceptor('token', rspLogin.token)
        intercept_channel = grpc.intercept_channel(channelAuth, header_adder_interceptor)
        order_stub = OrderReportingStub(intercept_channel)

        channelPublic = grpc.insecure_channel(Constants.HOST + ':' + Constants.PORT_PUBLIC)
        mdmStub = MarketDataManageStub(channelPublic)

        # maStrategy = ma_strategy.MaStrategy(mdmStub, order_stub)
        # maStrategy.start()
        # print(ma_strategy.strategy_name + " started, you could follow its logs in the output folder.")

        positionStrategy = position_strategy.PositionStrategy(mdmStub, order_stub)
        positionStrategy.start()
        print(position_strategy.strategy_name + " started, you could follow its logs in the output folder.")

        # Safely exit using keybord: Ctrl + c
        def shutdown(signal, frame):
            # maStrategy.stop()
            positionStrategy.stop()
            sys.exit()
        
        for sig in [signal.SIGINT, signal.SIGTERM]:
            signal.signal(sig, shutdown)

        while True:
            time.sleep(360)

if __name__ == '__main__':
    RouweiDemo()
    print('--end--')